#if defined(windows_x86) || defined(SYLIXOS) || defined(LINUX) || defined(MACOSX)

#ifndef KC1110_2_RTE_RETAIN_file_H
#define KC1110_2_RTE_RETAIN_file_H

#include <cstdio>
#include "logger_rte.h"
#include "mem_block.h"
#define LFS_NAME_MAX 32
class retain_file : public mem_block
{
public:
    void Remove(int i) override
    {
        if (::remove(filename[i]) != 0)
            logger.error("Error deleting file");
        else
            logger.info("File successfully deleted");
    }

    int Read(u8 block, unsigned int i, unsigned int len, void *pVoid) override
    {
        FILE *fd;
        int size;
        logger.debug("Read %s", filename[i]);
        fd = fopen(filename[i], "rb");
        if (fd)
        {
            size = fread(pVoid, 1, len, fd);
            fclose(fd);
        }
        return size;
    }

    void Write(unsigned char i, unsigned int i2, void *pVoid, unsigned int len) override
    {
        FILE *fd;
        logger.debug("Write %s", filename[i]);
        fd = fopen(filename[i], "wb");
        if (fd)
        {
            fwrite(pVoid, 1, len, fd);
            fclose(fd);
        }
    }

    void begin(const char *name, int sz) override
    {
        logger.error("Not implemented: begin(const char *name, int sz)");
    };

    int begin(byte *, byte sz)
    {
        logger.error("Not implemented: begin(byte *, byte sz)");
        return 0;
    };

    int Write(byte *dat, int len) override
    {
        FILE *fd;
        logger.debug("Write %s", filename[0]);
        fd = fopen(filename[0], "ab");
        if (fd)
        {
            fwrite(dat, 1, len, fd);
            fclose(fd);
        }
        return 0;
    };
    int dat_len{}, pos{};
    int begin(byte *name, byte name_sz, uint32_t start_address, uint32_t data_len) override
    {
        dat_len = data_len;
        u8 key_len = strlen((const char *)(name));
        if (key_len > name_sz)
            return -1;
        memset(filename[0], 0, LFS_NAME_MAX);
        memcpy(filename[0], name, name_sz);
        Remove(0);
        return (4096 - 16) * 7 / 8;
    };

    const char *name() override { return "file"; }

    int begin_read(byte *name, byte name_sz, uint32_t start_address, uint32_t data_len)
    {
        logger.error("Not implemented: begin_read(byte *name, byte name_sz, uint32_t start_address, uint32_t data_len)");
        return 0;
    };

private:
    char filename[2][LFS_NAME_MAX] = {};
};

#endif // KC1110_2_RTE_RETAIN_file_H
#endif
